package com.hmall.trade.listener;

import com.hmall.api.client.PayClient;
import com.hmall.api.dto.PayOrderDTO;
import com.hmall.common.constant.MQConstants;
import com.hmall.common.constant.OrderConstants;
import com.hmall.common.constant.PayOrderConstants;
import com.hmall.trade.domain.po.Order;
import com.hmall.trade.service.IOrderService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * @author 勾新杰
 * @version 1.0
 * @date 2024/10/17 15:59
 */
@Component
@RequiredArgsConstructor
public class DelayOrderListener {

    private final IOrderService orderService;
    private final PayClient payClient;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MQConstants.DELAY_ORDER_QUEUE_NAME, durable = "true"),
            exchange = @Exchange(name = MQConstants.DELAY_ORDER_EXCHANGE_NAME, delayed = "true"),
            key = MQConstants.DELAY_ORDER_ROUTING_KEY
    ))
    public void listenDelayOrder(Long orderId){
        // 1、查询订单状态
        Order order = orderService.getById(orderId);
        Integer status = order.getStatus();
        // 2、订单状态为已支付，啥也不做，退出
        if (status.equals(OrderConstants.PAID)){
            return;
        }
        // 3、订单状态未支付，则查询支付单的状态
        if (status.equals(OrderConstants.UNPAID)){
            PayOrderDTO payOrderDTO = payClient.queryPayOrderByBizOrderNo(orderId);
            // 4、支付单状态为已支付，则修改订单状态为已支付，退出
            if (payOrderDTO != null && payOrderDTO.getStatus().equals(PayOrderConstants.PAY_SUCCESS)){
                orderService.markOrderPaySuccess(orderId);
            }
            // 5、支付单状态为未支付，则修改订单状态为已取消，库存复原，退出
            else {
                orderService.cancelOrder(orderId);
            }
        }
    }
}
